from pms.common.views import PostFormula
from user.models import Role, User
from django.db.models.deletion import ProtectedError


class API(PostFormula):

    require_permissions = [12]

    def handle(self, req):
        try:
            rid = req['id']
            role = Role.objects.get(id=rid)
            delete_rid = role.id
            role.delete()
            return self.success_respond({
                'id': delete_rid
            })
        except ProtectedError as e:
            protected_object = e.protected_objects.pop()
            if isinstance(protected_object, User):
                return self.failed_respond('USER_RID_PROTECT', '{}({})用户具有该身份，故不能删除'
                                           .format(protected_object.name, protected_object.id))
